<?php
// $Id: table_album_cat.php 364 2012-05-10 09:31:35Z tomqin@gmail.com $

class Table_Album_Cat_Module{
    public $user = null;

    public function __construct($user){
        $this->user = $user;
    }

    public function check_user_right($shop_id){
        if($this->user->status == USER_ADMIN){
            return true;
        }elseif($this->user->status == USER_BUSINESS){
            $uid = $this->user->uid;
            $shop_id = intval($shop_id);
            return Db::getFirst("SELECT count(shop_id) FROM `biz_shop` WHERE admin_uid = '$uid' AND shop_id = '$shop_id'");
        }else{
            return false;
        }
    }

    public function get_list($shop_id){
        $shop_id = intval($shop_id);
        return Db::getKeyArray("SELECT * FROM `biz_album_cat` WHERE `shop_id` = '{$shop_id}' ORDER BY ordnum DESC", 'album_cat');
    }

    public function insert(array $post){
        $data = $this->album_cat_fields($post);
        unset($data['album_cat']);
        return Db::insert('biz_album_cat', $data);
    }

    public function update($shop_id, $album_cat, array $post){
        $shop_id = intval($shop_id);
        $album_cat = intval($album_cat);
        $data = array('cat_name' => array_get_string($post, 'cat_name'));
        return Db::update('biz_album_cat', $data, array('shop_id' => $shop_id, 'album_cat' => $album_cat));
    }

    public function delete($shop_id, $album_cat){
        $shop_id = intval($shop_id);
        $album_cat = intval($album_cat);
        Db::query("DELETE FROM `biz_album_cat` WHERE shop_id = '{$shop_id}' AND album_cat = '{$album_cat}'");
        return true;
    }

    public function upgrade($shop_id, array $post){
        $shop_id = intval($shop_id);
        $stmt = Db::prepare('UPDATE `biz_album_cat` SET cat_name = ?, ordnum = ? WHERE album_cat = ? AND shop_id = ?');
        $stmt->bind_param('siii', $cat_name, $ordnum, $album_cat, $shop_id);
        foreach($post['sorts'] as $album_cat => $ordnum){
            $cat_name = $post['names'][$album_cat];
            $stmt->execute();
        }
        return true;
    }

    public function get_data($shop_id, $album_cat){
        $shop_id = intval($shop_id);
        $album_cat = intval($album_cat);
        return Db::getRow("SELECT * FROM `biz_album_cat` WHERE `shop_id` = '{$shop_id}' AND `album_cat` = '{$album_cat}'");
    }

    protected function album_cat_fields($post){
        return array(
            'album_cat'  => array_get_int($post, 'album_cat'),
            'shop_id'    => array_get_int($post, 'shop_id'),
            'cat_name'   => array_get_string($post, 'cat_name'),
            'ordnum'     => array_get_int($post, 'ordnum'),
        );
    }
}
?>